package com.cutie.user.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.cutie.core.dao.DBManager;
import com.cutie.core.dao.IBuilder;
import com.cutie.user.model.User;

public class UserDao {

	private static final String register_sql = "insert into user(name,email,password) values(?,?,?)";
	public void register(User user) throws SQLException{
		
		try{
			Object[] data = new Object[]{ user.getName(), user.getEmail(), user.getPassword()};
			DBManager.executeUpdate(register_sql, data);
		}catch(SQLException e){
			e.printStackTrace();
			throw e;
		}
	}
	
	private static final String exist_name_sql = "select count(*) from user where name=?";
	public boolean existName(User user) throws SQLException{
		try{
			Object[] data = new Object[]{ user.getName()};
			Boolean exist = (Boolean)DBManager.executeQuery(exist_name_sql, data, new IBuilder(){

				@Override
				public Object build(ResultSet rs) throws SQLException {
					if(rs.next() && rs.getInt(1)>0){
						return true;
					}
					return false;
				}
				
			});
			
			return exist;
		}catch(SQLException e){
			e.printStackTrace();
			throw e;
		}
	}

	private static final String exist_email_sql = "select count(*) from user where email=?";
	public boolean existEmail(User user) throws SQLException{
		try{
			Object[] data = new Object[]{ user.getEmail()};
			Boolean exist = (Boolean)DBManager.executeQuery(exist_email_sql, data, new IBuilder(){

				@Override
				public Object build(ResultSet rs) throws SQLException {
					if(rs.next() && rs.getInt(1)>0){
						return true;
					}
					return false;
				}
				
			});
			
			return exist;
		}catch(SQLException e){
			e.printStackTrace();
			throw e;
		}
	}
	
	private static final String login_sql = "select count(*) from user where name=? and password=?";
	public boolean login(User user) throws SQLException{
		try{
			Object[] data = new Object[]{ user.getName(), user.getPassword()};
			Boolean pass = (Boolean)DBManager.executeQuery(login_sql, data, new IBuilder(){

				@Override
				public Object build(ResultSet rs) throws SQLException {
					if(rs.next() && rs.getInt(1)>0){
						return true;
					}
					return false;
				}
				
			});
			
			return pass;
		}catch(SQLException e){
			e.printStackTrace();
			throw e;
		}
	}
}
